#! /usr/bin/env python3
import os
import sys
sys.path.append(os.path.dirname(os.getcwd()))
import cgi
import json
from urllib import parse
from convertMdUtil import convertToMdHtml
import loginWeb

_PLATFORM = "win" in sys.platform and "windows" or "linux"


def login():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    loginWeb.main(note_path, except_list)


def get_config(path="config.json"):
    with open(path, "r+", encoding="utf-8") as f:
        json_dict = json.load(f)
        return json_dict


def get_md_path():
    cgi_mod = cgi.FieldStorage()
    file_label = cgi_mod.getvalue('file')
    file_path = parse.unquote(file_label)
    return file_path


def get_md_html(body, sel):
    head = "Content-type:text/html\n\n"
    with open("html/md.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(name=os.path.basename(get_md_path()), main=body, ci_float=sel)
        return head + constent


def get_sel_part(add_sel=""):
    result = ""
    with open("html/float2.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        result = constent.format(seli=add_sel)
    return result


def main():
    script_path = os.getcwd()
    result = "\n"
    result += convertToMdHtml.md_covert(get_config().get("note_path", {}).get(_PLATFORM, None) + "/" + get_md_path(), get_md_path(), script_path)
    return get_md_html(result, sel=get_sel_part())


if __name__ == "__main__":
    config = get_config()
    cgi_mod = cgi.FieldStorage()
    pass_list = config.get("passwd", None)
    states = False
    try:
        cookies = os.getenv("HTTP_COOKIE")
        exec(cookies)
        if state in pass_list:
            states = True
    except Exception:
        pass
    if states is False:
        login()
    else:
        print(main())
